package com.rules.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;


import com.gillion.grule.client.core.BusinessModelAttribute;
import com.rules.admin.dao.BusinessModelDao;
import com.rules.admin.entity.BusinessModel;
import com.rules.admin.entity.BusinessModelAttributeEntity;
import com.rules.admin.service.BusinessModelAttributeService;
import com.rules.admin.service.BusinessModelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BusinessModelServiceImpl extends ServiceImpl<BusinessModelDao, BusinessModel> implements BusinessModelService {

   @Autowired
   private BusinessModelAttributeService businessModelAttributeService;


   public BusinessModel insert(BusinessModel businessModel) {
      this.save(businessModel);
      return businessModel;
   }

   public BusinessModel update(BusinessModel BusinessModel) {
      this.updateById(BusinessModel);
      return BusinessModel;
   }

   public void delete(long id) {
      this.removeById(id);
      this.businessModelAttributeService.deleteByBusinessModel(id);
   }



   public List<BusinessModelAttribute> getModelAttributes(long id) {
      List<BusinessModelAttributeEntity> oldList = this.businessModelAttributeService.getModelAttributesByModelId(id);
      List<BusinessModelAttribute> newList = new ArrayList<>();
      oldList.stream().forEach(item->{
         BusinessModelAttribute modelAttribute = new BusinessModelAttribute();
         BeanUtils.copyProperties(item, modelAttribute);
         newList.add(modelAttribute);
      });

      return newList;


   }

   public IPage<BusinessModel> queryPage(String name, IPage<BusinessModel> page) {
      LambdaQueryWrapper<BusinessModel> queryWrapper = new LambdaQueryWrapper<>();
      if (StringUtils.isNotBlank(name)) {
         queryWrapper.like(BusinessModel::getName, "%" + name + "%");
      }
      return this.page(page, queryWrapper);


   }

   public BusinessModel findByName(String name) {
      if (StringUtils.isBlank(name)) {
         return null;
      } else {
         return this.baseMapper.selectOne(Wrappers.<BusinessModel>lambdaQuery().eq(BusinessModel::getName, name));

      }
   }
}
